<?php

namespace App\Kuafu\Customer\Service;

use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Activity\Service\ActivityService;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Customer\Model\CustomerActionLogModel;
use App\Kuafu\Customer\Model\CustomerPlatformModel;
use App\Kuafu\Mqtt\Service\MqttService;
use App\Kuafu\Shop\Enum\ShopCacheEnum;
use App\Kuafu\Wechat\Enum\CodeEnum;
use App\Support\AppletEncrypt;
use Illuminate\Database\Eloquent\Builder;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CustomerActionLogService extends BaseService
{
    private string $unionId = '';

    public function setUnionIdByUserId(?int $userId): CustomerActionLogService
    {
        $customerFirst = CustomerPlatformModel::query()
                                              ->where('userId', $userId)
                                              ->where('unionid', '!=', '')
                                              ->withoutGlobalScope('isDel')
                                              ->first();

        $this->unionId = $customerFirst->unionid ?? '';
        return $this;
    }


    /**
     * 单独处理公众号用户日志数据
     *
     * @return void
     */
    public function dealOfficeUserData(array $postData, $userInfo)
    {
        $shopId     = 0;
        $activityId = 0;
        try {
            if (!empty($postData['EventKey'])) {
                list(, $jsonStr) = explode(':', $postData['EventKey']);
                $decryptShort = AppletEncrypt::getInstance()->decryptShort($jsonStr, CodeEnum::APPLET_EVENT_KEY);
                $qrCodeData   = json_decode($decryptShort, true);
                $shopId       = $qrCodeData['shopId'] ?? 0;

                $activityId = ActivityService::getActivityIdByShopInfo(ActivityEnum::TYPE_START_BUSINESS_ACTIVITY,
                    $shopId);
            }
        } catch (\Exception $e) {
            Log::error('公众号关注日志解析失败', [
                'postData' => $postData,
                'userInfo' => $userInfo
            ]);
        }

        // 公众号关注
        (new CustomerActionLogService())->asynSaveData([
            'userId'   => $userInfo->userId ?? 0,
            'unionId'  => $userInfo->unionid,
            'type'     => CustomerActionLogModel::ACTION_TYPE_OFFICIAL_FOLLOW,
            'userInfo' => [
                'shopId'     => $shopId,
                'openId'     => $userInfo->openid,
                'activityId' => $activityId,
                'codeType'   => $qrCodeData['type'] ?? 0,
            ]
        ]);
    }


    public function asynSaveData(array $data)
    {
        if (empty($data['unionId'])) {
            $data['unionId'] = $this->unionId;
        }

//        dispatch(function () use ($data) {
        $userInfo = empty($data['userInfo']) ? null : json_encode($data['userInfo']);
        // 添加异步日志
        $customerActionLogModel           = new CustomerActionLogModel();
        $customerActionLogModel->userId   = $data['userId'] ?? 0;
        $customerActionLogModel->unionId  = $data['unionId'] ?? '';
        $customerActionLogModel->type     = $data['type'] ?? 0;
        $customerActionLogModel->userInfo = $userInfo;
        $customerActionLogModel->save();
//        });
    }
}
